package com.cellulam.framework.fs.excel.reader;

import com.cellulam.framework.fs.common.DataTable;
import com.cellulam.framework.fs.excel.model.ExcelFileType;
import com.cellulam.framework.fs.excel.model.RowNumber;
import com.cellulam.framework.fs.exception.ExcelFileReadException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 */
public class ExcelReader {

    private static final Logger logger = LoggerFactory.getLogger(ExcelReader.class);

    /**
     * @param is
     * @param excelClass
     * @param fileType
     * @param <T>
     * @return
     */
    public <T extends RowNumber> List<T> readAsList(InputStream is, Class<T> excelClass, ExcelFileType fileType) {
        SimpleTableReader str = new SimpleTableReader(readAsWorkbook(is, fileType));
        return str.readAsList(excelClass, 0, 1);
    }

    /**
     * 读取流为data-table
     *
     * @param is
     * @return
     */
    public static DataTable readAsDataTable(InputStream is, ExcelFileType fileType) {
        SimpleTableReader str = new SimpleTableReader(readAsWorkbook(is, fileType));
        DataTable dt = new DataTable();
        List<List<String>> lis = str.readAsStringRows(0, 0);
        List<String> headers = lis.remove(0);
        dt.setHeaders(headers);
        dt.setDataRows(lis);
        return dt;
    }

    /**
     * 读取 流,
     * 最后关闭流
     *
     * @param is
     * @return
     */
    public static Workbook readAsWorkbook(InputStream is, ExcelFileType fileType) {
        try {
            switch (fileType) {
                case XLS:
                    return new HSSFWorkbook(is);
                case XLSX:
                    return new XSSFWorkbook(is);
                default:
                    throw new RuntimeException("unknown file suffix#" + fileType);
            }
        } catch (Exception e) {
            throw new ExcelFileReadException("get workbook by stream error", e);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    /**
     * 读取 本地文件,
     * 最后关闭流
     *
     * @param localFile
     * @return
     */
    public static Workbook readAsWorkbook(File localFile, ExcelFileType fileType) {
        try {
            return readAsWorkbook(FileUtils.openInputStream(localFile), fileType);
        } catch (IOException e) {
            throw new ExcelFileReadException("get workbook by local-file error", e);
        }
    }

    /**
     * 读取 本地文件, 自动识别后缀
     * 最后关闭流
     *
     * @param localFile
     * @return
     */
    public static Workbook readAsWorkbook(File localFile) {
        return readAsWorkbook(localFile, detectExcelType(localFile));
    }

    /**
     * 检测 excel文件类型
     *
     * @param localFile
     * @return
     */
    public static ExcelFileType detectExcelType(File localFile) {
        return detectExcelType(localFile.getName());
    }

    /**
     * 检测 excel文件类型, 通过文件名 后缀
     *
     * @param fileName
     * @return
     */
    public static ExcelFileType detectExcelType(String fileName) {
        String suffix = StringUtils.substringAfterLast(fileName, ".");
        return detectExcelTypeByExtension(suffix);
    }

    /**
     * 检测 excel文件类型, 通过文件名 后缀
     *
     * @param extension
     * @return
     */
    public static ExcelFileType detectExcelTypeByExtension(String extension) {
        if (StringUtils.endsWithIgnoreCase(extension, ExcelFileType.XLS.getDescription())) {
            return ExcelFileType.XLS;
        } else if (StringUtils.endsWithIgnoreCase(extension, ExcelFileType.XLSX.getDescription())) {
            return ExcelFileType.XLSX;
        } else {
            return null;
        }
    }

}
